//
// Created by tonystark on 16/3/31.
// Copyright (c) 2016 sewm. All rights reserved.
//

#import "YouDaoSearchResultsView.h"

#define BottomBarHeight 44

@interface YouDaoSearchResultsView () {
    CGFloat _startedY;
    UILabel *_warningLabel;
    UIView *_warningView;
    BOOL _shouldRemvoveObserver;
}
@end

@implementation YouDaoSearchResultsView {

}
- (void)dealloc {
    //移除观察者
    [self removeBtnObserver];
    _searchBar = nil;
    _searchResultsTableView = nil;
    _warningLabel = nil;
}

- (id)init {
    self = [super init];
    if (self) {
        self.frame = CGRectMake(0, 0, deviceWidth, deviceHeight);
        self.backgroundColor = UIColorFromRGB(0xFFFFFF);

        UIView *topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, deviceWidth, GAP20 + topBarHeight)];
        topView.backgroundColor = topBarColor;
        [self addSubview:topView];

        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, GAP20, deviceWidth, topBarHeight)];
        _searchBar.placeholder = @"搜索";
        _searchBar.delegate = self;
        _searchBar.barTintColor = UIColorFromRGB(0xF7F7F7);
        _searchBar.translucent = NO;
        [[[[_searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
        _searchBar.backgroundColor = topBarColor;

        [self addSubview:_searchBar];
    }
    return self;
}

- (UIView *)warningView {
    if (!_warningView) {
        _warningView = [[UIView alloc] initWithFrame:_searchResultsTableView.bounds];
        _warningView.backgroundColor = UIColorFromRGB(0xffffff);

        UIImage *image = [UIImage imageNamed:@"noresult"];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((deviceWidth - image.size.width) / 2.0, (_warningView.frameHeight - image.size.height) / 2.0 - image.size.height, image.size.width, image.size.height)];
        imageView.image = image;
        [_warningView addSubview:imageView];

        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.frameMaxY + 10, deviceWidth, 30)];
        titleLab.font = [UIFont systemFontOfSize:15];
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = UIColorFromRGB(0x666666);
        titleLab.text = @"抱歉 暂无您搜索的信息";
        [_warningView addSubview:titleLab];
    }
    return _warningView;
}

#pragma mark - 开启取消按钮

- (void)addBtnObserver {
    _shouldRemvoveObserver = YES;
    // Search for Cancel button in searchbar, enable it and add key-value observer.
    for (UIView *view in [self.searchBar subviews]) {
        for (id subview in [view subviews]) {
            if ([subview isKindOfClass:[UIButton class]]) {
                [subview setEnabled:YES];
                [subview addObserver:self forKeyPath:@"enabled" options:NSKeyValueObservingOptionNew context:nil];
                [subview setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateNormal];
                [subview setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateHighlighted];
                [subview setTitleColor:UIColorFromRGB(0xffffff) forState:UIControlStateSelected];
                [subview setTitle:@"取消" forState:UIControlStateNormal];
            }
        }
    }
}

- (void)removeBtnObserver {
    if (_shouldRemvoveObserver) {
        _shouldRemvoveObserver = NO;
        // Remove observer for the Cancel button in searchBar.
        for (UIView *view in [self.searchBar subviews]) {
            for (id subview in [view subviews]) {
                if ([subview isKindOfClass:[UIButton class]])
                    [subview removeObserver:self forKeyPath:@"enabled"];
            }
        }
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    // Re-enable the Cancel button in searchBar.
    if ([object isKindOfClass:[UIButton class]] && [keyPath isEqualToString:@"enabled"]) {
        UIButton *button = object;
        if (!button.enabled)
            button.enabled = YES;
    }
}

#pragma mark - public

- (void)showWithBlock:(NoparamBlock)block startedPoint:(CGPoint)pt {
    block();
    self.frameY = pt.y;
    _startedY = self.frameY;
    _searchBar.backgroundColor = topBarColor;
    [UIView animateWithDuration:0.25f animations:^{
        self.frameY = 0;
    }                completion:^(BOOL finished) {
        if ([self.delegate respondsToSelector:@selector(dishSearchResultsViewDidShow:)]) {
            [self.delegate dishSearchResultsViewDidShow:self];
        }
    }];
    [_searchBar becomeFirstResponder];
    [_searchBar setShowsCancelButton:YES animated:YES];
    [self addBtnObserver];
}

- (void)showInView:(UIView *)view startedPoint:(CGPoint)pt {
    self.frameY = pt.y;
    _startedY = self.frameY;
    [view addSubview:self];
    _searchBar.backgroundColor = topBarColor;
    [UIView animateWithDuration:0.25f animations:^{
        self.frameY = 0;
    }                completion:^(BOOL finished) {
        if ([self.delegate respondsToSelector:@selector(dishSearchResultsViewDidShow:)]) {
            [self.delegate dishSearchResultsViewDidShow:self];
        }
    }];
    [_searchBar becomeFirstResponder];
    [_searchBar setShowsCancelButton:YES animated:YES];
    [self addBtnObserver];
}

- (void)hide:(BOOL)animated {
    _searchBar.text = @"";
    [_searchBar resignFirstResponder];
    [_searchBar setShowsCancelButton:NO animated:YES];
    _searchBar.backgroundColor = UIColorFromRGB(0xeff0f0);
    [UIView animateWithDuration:0.25f animations:^{
        self.frameY = _startedY;
    }                completion:^(BOOL finished) {
        [self removeFromSuperview];
        // 移除UITableView，当输入文本时再创建
        [_searchResultsTableView removeFromSuperview];
        _searchResultsTableView = nil;
        if ([self.delegate respondsToSelector:@selector(dishSearchResultsViewDidHide:)]) {
            [self.delegate dishSearchResultsViewDidHide:self];
        }
    }];
    if ([self.delegate respondsToSelector:@selector(dishSearchResultsViewWillHide:)]) {
        [self.delegate dishSearchResultsViewWillHide:self];
    }
    [self removeBtnObserver];
}

#pragma mark - UISearchBarDelegate

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [_searchResultsTableView forceStopScrolling];
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    if (searchBar.text.length > 0) {
        searchBar.text = @"";
        [self searchBar:searchBar textDidChange:searchBar.text];
    }
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (!_searchResultsTableView) {
        // 创建TableView
        _searchResultsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, GAP20 + topBarHeight, deviceWidth, deviceHeight - GAP20 - topBarHeight - BottomBarHeight)];
        _searchResultsTableView.backgroundColor = [UIColor clearColor];
        _searchResultsTableView.dataSource = self.searchResultsDataSource;
        _searchResultsTableView.delegate = self.searchResultsDelegate;
        _searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        [_searchResultsTableView registerClass:[DishCell class] forCellReuseIdentifier:@"DishCell"];
        [self addSubview:_searchResultsTableView];

        // 点击隐藏键盘
        [_searchResultsTableView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)]];
    }
    [self.delegate dishSearchResultsView:self filterWithSearchString:searchText];
    [_searchResultsTableView reloadData];
    if (searchText.length > 0 && [_searchResultsTableView numberOfRowsInSection:0] == 0) {
        // 无结果
        _searchResultsTableView.tableHeaderView = [self warningView];
    } else {
        _searchResultsTableView.tableHeaderView = nil;
    }
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    // 点击搜索隐藏键盘
    [_searchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self hide:YES];
}

- (void)dismissKeyboard {
    [self hideSearchKeyboard];
}

/**
 * 隐藏搜索界面的键盘
 */
- (void)hideSearchKeyboard {
    if ([_searchBar isFirstResponder]) {
        [_searchBar resignFirstResponder];
    }
}
@end